<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
		pre {font-size: 5px; height: 120px;}
	</style>
	<!--<script src="jquery-1.9.0.min.js"></script>-->
	<script type="text/javascript">

    function ab2str(buf) {
        return String.fromCharCode.apply(null, new Uint16Array(buf));
    }
    function str2ab(str) {
        var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
        var bufView = new Uint16Array(buf);
        for (var i=0, strLen=str.length; i < strLen; i++) {
            bufView[i] = str.charCodeAt(i);
        }
        return buf;
    }

    function utf8AbFromString(str) {
        var strUtf8 = unescape(encodeURIComponent(str));
        var ab = new Uint8Array(strUtf8.length);
        for (var i = 0; i < strUtf8.length; i++) {
            ab[i] = strUtf8.charCodeAt(i);
        }
        return ab;
    }
    function stringFromUtf8Ab(ab) {
        return decodeURIComponent(escape(String.fromCharCode.apply(null, ab)));
    }

    var MessageType = {
        Raw: 0,
        Hello: 1,
        HeartBeat: 2,
        StreamStart: 3,
        Streaming: 4,
        StreamEnd: 5,
        String: 6,
        Data: 7
    };

    let socket = (function () {

        var reconnectAttempts = 0;
        var reConnnectTimeInterval = [1, 2, 4, 8, 16];
        var websocket;

        function ws_connect() {

            websocket = new WebSocket('ws://127.0.0.1:12345/service');
            websocket.binaryType = 'arraybuffer';

            websocket.onopen = function () {
                // 建立连接，将重试次数重置
                reconnectAttempts = 0;
                console.log("socket opened");
                window.webkit.messageHandlers.nativelog.postMessage('websocket 连接打开成功');

                sendHeartBeat();
            };

            websocket.onerror = function () {
                window.webkit.messageHandlers.nativelog.postMessage('websocket 连接打开失败');
            };

            websocket.onclose = function () {
                window.webkit.messageHandlers.nativelog.postMessage('websocket 连接关闭');
                // 重连
                reConnect()
            };


            websocket.onmessage = function (message) {
                var data = message.data;
                if (data instanceof ArrayBuffer) {

                    // 前4个字节appId
                    var headerLen = 4;
                    var buf = data.slice(0, headerLen);

                    var dv = new DataView(buf, 0);

                    // 小端
                    var messageType = dv.getUint32(0, true);

                    var len = data.byteLength;
                    var buf3 = data.slice(headerLen, len);

                    //todo: receive data 处理
                    console.log('=== messageType:' + messageType + ' text:' + ab2str(buf3));


                    // 收到数据，直接发回去，为了测试
                    websocket.send(data)
                }
            };
        }

        // 重连
        function reConnect() {
            window.webkit.messageHandlers.nativelog.postMessage('websocket 重新连接...');
            reconnectAttempts++;
            if (reconnectAttempts > reConnnectTimeInterval.length) {
                return;
            }

            var timeOut = reConnnectTimeInterval[reconnectAttempts - 1];

            setTimeout(function () {
                ws_connect();
            }, timeOut)
        }

        var timeIntervalID;
        function sendHeartBeat() {
            if (timeIntervalID) {
                clearInterval(timeIntervalID);
            }

            timeIntervalID = window.setInterval(function () {
                if (websocket) {
                    websocket.send(
                        JSON.stringify({'messageType': MessageType.Hello})
                    );
                }
            }, 5000);
        }


        return {
            connect: function() {
                ws_connect();
            },
            sendString: function(body='') {
                websocket.send(
                    JSON.stringify({'messageType': MessageType.String, 'messageBody': body })
                );
            },
            sendData: function(body=null) {
                websocket.send(
                    JSON.stringify({'messageType': MessageType.Data, 'messageBody': body })
                );
            },
			sendStreamStart: function() {
                websocket.send(
                    JSON.stringify({'messageType': MessageType.StreamStart, 'messageBody': null })
                );
            },
            sendStreaming: function(body=null) {
                websocket.send(
                    JSON.stringify({'messageType': MessageType.Streaming, 'messageBody': body })
                );
            },
            sendStreamEnd: function() {
                websocket.send(
                    JSON.stringify({'messageType': MessageType.StreamEnd, 'messageBody': null })
                );
            },
        };

    })();



	</script>
</head>


<body>
	<h2>WebSockets echo client with push support</h2>
	<form>
		<input type="text" placeholder="message to be echoed"/>
		<button>Send</button>
	</form>
	<h4>Echo result :</h4>
	<p></p>
	<h4>Pushed messages :</h4>
	<pre></pre>
</body>
</html>
